package org.listbeast.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.ProxySelector;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.listbeast.core.common.ApplicationException;
import org.listbeast.core.common.ApplicationInformationImpl;
import org.listbeast.core.common.ValidationException;

import com.btr.proxy.search.ProxySearch;
import com.btr.proxy.search.ProxySearch.Strategy;
import com.btr.proxy.util.PlatformUtil;
import com.btr.proxy.util.PlatformUtil.Platform;

/**
 * This is the main class of the application. It loads the properties file and
 * starts the application.
 * 
 * @author ody
 * 
 */
public class ListBeastMain {

	private static final Logger LOG = Logger.getLogger(ListBeastMain.class);
	private static final Properties PROPS = new Properties();

	static {
		Writer out = new StringWriter();
		try {
			loadProperties(out);
		} catch (IOException e) {
			LOG.error(e);
		}
	}

	public static void main(String[] args) {

    	loadProxySettings();
    	
		ListBeastApp myApp;
		try {
			myApp = new ListBeastApp(PROPS.getProperty("targetDir"),
					PROPS.getProperty("sourceDir"), Integer.valueOf(PROPS
							.getProperty("maxYoutubeResults")),
					Boolean.valueOf(PROPS.getProperty("copySongs")),
					Boolean.valueOf(PROPS.getProperty("multiplePlaylists")));

			Thread popApp = new Thread(myApp);
			popApp.start();
		} catch (ValidationException e) {
			e.printStackTrace();
		}

	}

	private static void loadProxySettings() {
		ProxySearch proxySearch = new ProxySearch();
        
    	if (PlatformUtil.getCurrentPlattform() == Platform.WIN) {
    	  proxySearch.addStrategy(Strategy.IE);
    	  proxySearch.addStrategy(Strategy.FIREFOX);
    	  proxySearch.addStrategy(Strategy.JAVA);
    	} else 
    	if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) {
    	  proxySearch.addStrategy(Strategy.GNOME);
    	  proxySearch.addStrategy(Strategy.KDE);
    	  proxySearch.addStrategy(Strategy.FIREFOX);
    	} else {
    	  proxySearch.addStrategy(Strategy.OS_DEFAULT);
    	}

    	ProxySelector myProxySelector = proxySearch.getProxySelector();
    	                
    	ProxySelector.setDefault(myProxySelector);
	}

	private static void loadProperties(Writer out) throws IOException {
		// try retrieve data from file
		// kai ta dyo douleuoyn. to afhnw giati me ekapse mexri na to brw. balto
		// sto classpath
		// props.load(ListBeastMain.class.getResourceAsStream("/application.properties"));

		InputStream is = ListBeastMain.class.getClassLoader()
				.getResourceAsStream("application.properties");
		IOUtils.copy(is, out);

		// replace back-slash with slash and load properties
		PROPS.load(new StringReader(out.toString().replace("\\", "/")));
	}
}
